<template>
  <div class="app-container">
    <!-- Tab切换 -->
    <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
      <!-- 排班记录Tab -->
      <el-tab-pane label="排班记录" name="roster">
        <!-- 顶部操作区域 -->
        <el-card class="operation-card">
          <el-row :gutter="20" justify="space-between" align="middle">
            <el-col :span="6">
              <el-date-picker v-model="searchForm.rosterDate" type="date" placeholder="选择排班日期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-col>
            <el-col :span="6">
              <el-select v-model="searchForm.personId" placeholder="选择人员" clearable style="width: 100%">
                <el-option v-for="person in personList" :key="person.id" :label="person.fullName" :value="person.id" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="searchForm.shiftId" placeholder="选择班次" clearable style="width: 100%">
                <el-option v-for="shift in classesList" :key="shift.departmentId" :label="shift.classesName"
                  :value="shift.departmentId" />
              </el-select>
            </el-col>
            <el-col :span="6" class="operation-buttons">
              <el-button type="primary" @click="handleSearch">
                <el-icon>
                  <search />
                </el-icon>搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon>
                  <refresh />
                </el-icon>重置
              </el-button>
            </el-col>
          </el-row>
        </el-card>

        <!-- 表格区域 -->
        <el-card class="table-card">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <plus />
            </el-icon>新增排班
          </el-button>
          <el-button type="success" @click="handleOneClickRoster">
            <el-icon><magic-stick /></el-icon>一键排班
          </el-button>

          <el-table :data="tableData" class="mt-2" border style="width: 100%" v-loading="loading"
            :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="rosterDate" label="排班日期" />
            <el-table-column prop="personName" label="人员姓名" />
            <el-table-column prop="shiftName" label="班次名称" />
            <el-table-column prop="startAt" label="开始时间" />
            <el-table-column prop="endAt" label="结束时间" />
            <el-table-column prop="workMinutes" label="工时(分钟)">
              <template #default="{ row }">
                {{ row.workMinutes || '--' }}
              </template>
            </el-table-column>
            <el-table-column prop="sourceType" label="来源">
              <template #default="{ row }">
                <el-tag :type="getSourceTypeTagType(row.sourceType)">
                  {{ getSourceTypeLabel(row.sourceType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEdit(row)">
                  <el-icon>
                    <edit />
                  </el-icon>编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(row.id)">
                  <el-icon>
                    <delete />
                  </el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination 
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" 
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" 
            class="pagination"
          />
        </el-card>
      </el-tab-pane>

      <!-- 周期模板管理Tab -->
      <el-tab-pane label="周期模板" name="cycle">
        <el-card class="operation-card">
          <el-row :gutter="20" justify="space-between" align="middle">
            <el-col :span="8">
              <el-input v-model="cycleSearchForm.cycleName" placeholder="输入周期名称" clearable style="width: 100%"
                @keyup.enter="handleCycleSearch" />
            </el-col>
            <el-col :span="8">
              <el-select v-model="cycleSearchForm.isEnabled" placeholder="启用状态" clearable style="width: 100%">
                <el-option label="启用" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-col>
            <el-col :span="8" class="operation-buttons">
              <el-button type="primary" @click="handleCycleSearch">
                <el-icon>
                  <search />
                </el-icon>搜索
              </el-button>
              <el-button @click="handleCycleReset">
                <el-icon>
                  <refresh />
                </el-icon>重置
              </el-button>
              <el-button type="primary" @click="handleAddCycle">
                <el-icon>
                  <plus />
                </el-icon>新增周期模板
              </el-button>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="table-card">
          <el-table :data="cycleTableData" border style="width: 100%" v-loading="cycleLoading">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="cycleCode" label="周期编码" />
            <el-table-column prop="cycleName" label="周期名称" />
            <el-table-column prop="cycleLenDays" label="周期长度(天)" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="isEnabled" label="状态">
              <template #default="{ row }">
                <el-tag :type="row.isEnabled === 1 ? 'success' : 'danger'">
                  {{ row.isEnabled === 1 ? '启用' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditCycle(row)">
                  <el-icon>
                    <edit />
                  </el-icon>编辑
                </el-button>
                <el-button link type="danger" @click="handleDeleteCycle(row.id)">
                  <el-icon>
                    <delete />
                  </el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination 
            :current-page="cyclePagination.currentPage"
            :page-size="cyclePagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" 
            :total="cyclePagination.total"
            @size-change="handleCycleSizeChange"
            @current-change="handleCycleCurrentChange" 
            class="pagination"
          />
        </el-card>
      </el-tab-pane>

      <!-- 月视图Tab -->
      <el-tab-pane label="月视图" name="calendar">
        <el-card class="operation-card">
          <el-row :gutter="20" justify="space-between" align="middle">
            <el-col :span="12">
              <el-date-picker 
                v-model="calendarDate" 
                type="month" 
                placeholder="选择月份" 
                value-format="YYYY-MM"
                @change="fetchMonthViewData" 
                style="width: 200px" 
              />
            </el-col>
            <el-col :span="12" class="operation-buttons">
              <el-button @click="prevMonth">
                <el-icon><arrow-left /></el-icon>上个月
              </el-button>
              <el-button @click="nextMonth">
                下个月<el-icon><arrow-right /></el-icon>
              </el-button>
              <el-button type="primary" @click="goToToday">
                今天
              </el-button>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="calendar-card">
          <div class="calendar-header">
            <div class="calendar-weekday" v-for="day in weekDays" :key="day">{{ day }}</div>
          </div>
          <div class="calendar-body">
            <div v-for="(week, weekIndex) in calendarWeeks" :key="weekIndex" class="calendar-week">
              <div v-for="day in week" :key="day.date" class="calendar-day" :class="{
                'current-month': day.isCurrentMonth,
                'today': day.isToday,
                'has-data': day.rosterData && day.rosterData.length > 0
              }" @click="handleDayClick(day)">
                <div class="day-header">
                  <span class="day-number">{{ day.day }}</span>
                  <span v-if="day.isToday" class="today-badge">今</span>
                </div>
                <div class="day-content">
                  <div v-for="roster in day.rosterData" :key="roster.id" class="roster-item"
                    @click.stop="handleRosterClick(roster, day)">
                    <el-tag size="small" :type="getRosterTagType(roster.sourceType)">
                      {{ roster.personName }} - {{ roster.shiftName }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增/编辑排班对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
      <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="排班日期" prop="rosterDate">
          <el-date-picker v-model="formData.rosterDate" type="date" placeholder="选择排班日期" value-format="YYYY-MM-DD"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="人员" prop="personId">
          <el-select v-model="formData.personId" placeholder="选择人员" style="width: 100%">
            <el-option v-for="person in personList" :key="person.id" :label="person.fullName" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="班次" prop="shiftId">
          <el-select v-model="formData.shiftId" placeholder="选择班次" style="width: 100%" @change="handleShiftChange">
            <el-option v-for="shift in classesList" :key="shift.departmentId" :label="shift.classesName"
              :value="shift.departmentId" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startAt">
          <el-time-picker v-model="formData.startAt" placeholder="选择开始时间" value-format="HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endAt">
          <el-time-picker v-model="formData.endAt" placeholder="选择结束时间" value-format="HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="来源" prop="sourceType">
          <el-select v-model="formData.sourceType" placeholder="选择来源" style="width: 100%">
            <el-option label="手工" :value="1" />
            <el-option label="模板生成" :value="2" />
            <el-option label="导入" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 一键排班对话框 -->
    <el-dialog v-model="oneClickDialogVisible" title="一键排班" width="500px" :close-on-click-modal="false">
      <el-form :model="oneClickForm" label-width="100px" :rules="oneClickRules" ref="oneClickFormRef">
        <el-form-item label="月份" prop="month">
          <el-date-picker v-model="oneClickForm.month" type="month" placeholder="选择月份" value-format="YYYY-MM"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="排班人员" prop="personId">
          <el-select v-model="oneClickForm.personId" placeholder="选择人员" style="width: 100%">
            <el-option v-for="person in personList" :key="person.id" :label="person.fullName" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="周期模板" prop="cycleId">
          <el-select v-model="oneClickForm.cycleId" placeholder="选择周期模板" style="width: 100%">
            <el-option v-for="cycle in cycleList" :key="cycle.id" :label="cycle.cycleName" :value="cycle.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="oneClickDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOneClickRoster">开始排班</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑周期模板对话框 -->
    <el-dialog v-model="cycleDialogVisible" :title="cycleDialogTitle" width="800px" :close-on-click-modal="false">
      <el-form :model="cycleFormData" label-width="100px" :rules="cycleRules" ref="cycleFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="周期编码" prop="cycleCode">
              <el-input v-model="cycleFormData.cycleCode" placeholder="请输入周期编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周期名称" prop="cycleName">
              <el-input v-model="cycleFormData.cycleName" placeholder="请输入周期名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="周期长度" prop="cycleLenDays">
              <el-input-number v-model="cycleFormData.cycleLenDays" :min="1" :max="31" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isEnabled">
              <el-radio-group v-model="cycleFormData.isEnabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input v-model="cycleFormData.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>

        <!-- 周期明细部分 -->
        <el-form-item label="周期明细" v-if="cycleFormData.cycleLenDays > 0">
          <div class="cycle-details">
            <div v-for="day in cycleFormData.cycleLenDays" :key="day" class="detail-item">
              <span class="day-label">第{{ day }}天：</span>
              <el-select 
                v-model="getSafeCycleItem(day).shiftId"
                placeholder="选择班次" 
                style="width: 200px"
                @change="(value) => handleCycleItemChange(day, value)"
              >
                <el-option 
                  v-for="shift in cycleClassesList" 
                  :key="shift.departmentId" 
                  :label="shift.classesName"
                  :value="shift.departmentId" 
                />
              </el-select>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cycleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCycleForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 日历排班详情对话框 -->
    <el-dialog v-model="calendarDetailVisible" :title="`${selectedDate} 排班详情`" width="600px">
      <el-table :data="selectedDayRosters" border>
        <el-table-column prop="personName" label="人员" />
        <el-table-column prop="shiftName" label="班次" />
        <el-table-column prop="startAt" label="开始时间" />
        <el-table-column prop="endAt" label="结束时间" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEditFromCalendar(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDeleteFromCalendar(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="calendarDetailVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleAddFromCalendar">新增排班</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Edit,
  Delete,
  Refresh,
  MagicStick,
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue'

// 导入API
import {
  getPersonList,
  getClassesList,
  getRosterRecordList,
  getRosterRecordDetail,
  addRosterRecord,
  updateRosterRecord,
  deleteRosterRecord,
  oneClickRoster,
  getCycleList,
  getCycleDetail,
  addCycle,
  updateCycle,
  deleteCycle,
  getCycleClassesList,
  getMonthViewData
} from '@/api/dispatch/affair/monthly_schedule'

// Tab相关
const activeTab = ref('roster')

// 搜索表单
const searchForm = reactive({
  rosterDate: '',
  personId: '',
  shiftId: ''
})

// 周期搜索表单
const cycleSearchForm = reactive({
  cycleName: '',
  isEnabled: ''
})

// 表格数据
const tableData = ref([])
const cycleTableData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const cyclePagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)
const cycleLoading = ref(false)
const calendarLoading = ref(false)

// 人员列表
const personList = ref([])
// 班次列表
const classesList = ref([])
// 周期模板列表
const cycleList = ref([])
// 周期班次列表
const cycleClassesList = ref([])
// 月视图数据
const monthViewData = ref([])

// 对话框相关
const dialogVisible = ref(false)
const oneClickDialogVisible = ref(false)
const cycleDialogVisible = ref(false)
const calendarDetailVisible = ref(false)
const dialogTitle = ref('新增排班')
const cycleDialogTitle = ref('新增周期模板')
const formRef = ref(null)
const oneClickFormRef = ref(null)
const cycleFormRef = ref(null)

// 表单数据
const formData = reactive({
  id: null,
  rosterDate: '',
  personId: '',
  personName: '',
  shiftId: '',
  shiftName: '',
  startAt: '',
  endAt: '',
  sourceType: 1
})

// 周期表单数据
const cycleFormData = reactive({
  id: null,
  cycleCode: '',
  cycleName: '',
  cycleLenDays: 7,
  description: '',
  isEnabled: 1,
  items: [
    {
      shiftId: '',
      shiftName: ''
    }
  ]
})

// 一键排班表单
const oneClickForm = reactive({
  month: '',
  personId: '',
  cycleId: ''
})

// 日历相关
const calendarDate = ref(new Date().toISOString().slice(0, 7)) // 当前月份 YYYY-MM
const selectedDate = ref('')
const selectedDayRosters = ref([])

// 星期数组
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 日历数据计算
const calendarWeeks = computed(() => {
  if (!calendarDate.value) return []
  
  const [year, month] = calendarDate.value.split('-').map(Number)
  const firstDay = new Date(year, month - 1, 1)
  const lastDay = new Date(year, month, 0)
  const daysInMonth = lastDay.getDate()
  
  // 获取当月第一天是星期几（0-6，0代表星期日）
  const firstDayOfWeek = firstDay.getDay()
  
  const weeks = []
  let currentWeek = []
  
  // 添加上个月的最后几天
  const prevMonthLastDay = new Date(year, month - 1, 0).getDate()
  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    const day = prevMonthLastDay - i
    const prevMonth = month === 1 ? 12 : month - 1
    const prevYear = month === 1 ? year - 1 : year
    const dateStr = `${prevYear}-${String(prevMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    
    currentWeek.push({
      day,
      date: dateStr,
      isCurrentMonth: false,
      isToday: false,
      rosterData: getRosterDataByDate(dateStr)
    })
  }
  
  // 添加当月的天数
  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    const isToday = dateStr === new Date().toISOString().slice(0, 10)
    
    currentWeek.push({
      day,
      date: dateStr,
      isCurrentMonth: true,
      isToday,
      rosterData: getRosterDataByDate(dateStr)
    })
    
    // 如果当前周已满7天，开始新的一周
    if (currentWeek.length === 7) {
      weeks.push([...currentWeek])
      currentWeek = []
    }
  }
  
 
  // 添加下个月的前几天
  if (currentWeek.length > 0) {
    let nextMonthDay = 1
    while (currentWeek.length < 7) {
      const nextMonth = month === 12 ? 1 : month + 1
      const nextYear = month === 12 ? year + 1 : year
      const dateStr = `${nextYear}-${String(nextMonth).padStart(2, '0')}-${String(nextMonthDay).padStart(2, '0')}`
      
      currentWeek.push({
        day: nextMonthDay,
        date: dateStr,
        isCurrentMonth: false,
        isToday: false,
        rosterData: getRosterDataByDate(dateStr)
      })
      nextMonthDay++
    }
    weeks.push(currentWeek)
  }
  
  return weeks
})

// 根据日期获取排班数据
const getRosterDataByDate = (date) => {
  return monthViewData.value.filter(item => item.rosterDate === date)
}

// 安全获取周期明细项的方法
const getSafeCycleItem = (day) => {
  const index = day - 1
 if(cycleFormData.details){
    cycleFormData.items = cycleFormData.details;
  }
  if (!cycleFormData.items[index]) {
    cycleFormData.items[index] = { shiftId: '' , dayIndex:day }
  }
  
  return cycleFormData.items[index]
}

// 处理周期明细项变化
const handleCycleItemChange = (day, value) => {
  const index = day - 1
  if (!cycleFormData.items[index]) {
    cycleFormData.items[index] = {}
  }
  cycleFormData.items[index].shiftId = value
}

// 表单验证规则
const rules = {
  rosterDate: [{ required: true, message: '请选择排班日期', trigger: 'change' }],
  personId: [{ required: true, message: '请选择人员', trigger: 'change' }],
  shiftId: [{ required: true, message: '请选择班次', trigger: 'change' }],
  startAt: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endAt: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

const cycleRules = {
  cycleCode: [{ required: true, message: '请输入周期编码', trigger: 'blur' }],
  cycleName: [{ required: true, message: '请输入周期名称', trigger: 'blur' }],
  cycleLenDays: [{ required: true, message: '请输入周期长度', trigger: 'change' }]
}

const oneClickRules = {
  month: [{ required: true, message: '请选择月份', trigger: 'change' }],
  personId: [{ required: true, message: '请选择人员', trigger: 'change' }],
  cycleId: [{ required: true, message: '请选择周期模板', trigger: 'change' }]
}

// Tab切换处理
const handleTabClick = (tab) => {
  if (tab.paneName === 'cycle') {
    fetchCycleList()
  } else if (tab.paneName === 'calendar') {
    fetchMonthViewData()
  }
}

// 获取来源类型标签
const getSourceTypeLabel = (type) => {
  const types = { 1: '手工', 2: '模板生成', 3: '导入' }
  return types[type] || '未知'
}

const getSourceTypeTagType = (type) => {
  const types = { 1: 'primary', 2: 'success', 3: 'warning' }
  return types[type] || 'info'
}

const getRosterTagType = (type) => {
  const types = { 1: 'primary', 2: 'success', 3: 'warning' }
  return types[type] || 'info'
}

// 获取人员列表
const fetchPersonList = async () => {
  try {
    const { data } = await getPersonList()
    personList.value = data || []
  } catch (error) {
    console.error('获取人员列表失败:', error)
    ElMessage.error('获取人员列表失败')
  }
}

// 班次变化处理
const handleShiftChange = (value) => {
  const item = classesList.value.find(item => item.departmentId == value)
  if (item) {
    formData.startAt = item.classesTime
    formData.endAt = item.endTime
  }
}

// 获取班次列表
const fetchClassesList = async () => {
  try {
    const { data } = await getClassesList()
    classesList.value = data || []
  } catch (error) {
    console.error('获取班次列表失败:', error)
    ElMessage.error('获取班次列表失败')
  }
}

// 获取周期班次列表
const fetchCycleClassesList = async () => {
  try {
    const { data } = await getCycleClassesList()
    cycleClassesList.value = data || []
  } catch (error) {
    console.error('获取周期班次列表失败:', error)
    ElMessage.error('获取周期班次列表失败')
  }
}

// 获取周期模板列表
const fetchCycleList = async () => {
  try {
    cycleLoading.value = true
    const params = {
      pageNum: cyclePagination.currentPage,
      pageSize: cyclePagination.pageSize,
      ...cycleSearchForm
    }
    const data = await getCycleList(params)
    cycleTableData.value = data.rows || []
    cyclePagination.total = data.total || 0
  } catch (error) {
    console.error('获取周期模板列表失败:', error)
    ElMessage.error('获取周期模板列表失败')
  } finally {
    cycleLoading.value = false
  }
}

// 获取排班记录列表
const fetchRosterRecordList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const data = await getRosterRecordList(params)
    tableData.value = data.rows || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('获取排班记录列表失败:', error)
    ElMessage.error('获取排班记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取月视图数据
const fetchMonthViewData = async () => {
  try {
    calendarLoading.value = true
    const { data } = await getMonthViewData({ yearMonth: calendarDate.value })
    monthViewData.value = data || []
  } catch (error) {
    console.error('获取月视图数据失败:', error)
    ElMessage.error('获取月视图数据失败')
  } finally {
    calendarLoading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchRosterRecordList()
}

const handleCycleSearch = () => {
  cyclePagination.currentPage = 1
  fetchCycleList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => { searchForm[key] = '' })
  pagination.currentPage = 1
  fetchRosterRecordList()
}

const handleCycleReset = () => {
  Object.keys(cycleSearchForm).forEach(key => { cycleSearchForm[key] = '' })
  cyclePagination.currentPage = 1
  fetchCycleList()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchRosterRecordList()
}

const handleCycleSizeChange = (val) => {
  cyclePagination.pageSize = val
  cyclePagination.currentPage = 1
  fetchCycleList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchRosterRecordList()
}

const handleCycleCurrentChange = (val) => {
  cyclePagination.currentPage = val
  fetchCycleList()
}

// 排班记录操作
const handleAdd = () => {
  dialogTitle.value = '新增排班'
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'sourceType' ? 1 : ''
  })
  formData.id = null
  dialogVisible.value = true
}

const handleEdit = async (row) => {
  try {
    loading.value = true
    const { data } = await getRosterRecordDetail(row.id)
    if (data) {
      dialogTitle.value = '编辑排班'
      Object.assign(formData, data)
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取排班详情失败:', error)
    ElMessage.error('获取排班详情失败')
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()

    const selectedPerson = personList.value.find(p => p.id === formData.personId)
    const selectedShift = classesList.value.find(s => s.departmentId === formData.shiftId)

    if (selectedPerson) formData.personName = selectedPerson.fullName
    if (selectedShift) formData.shiftName = selectedShift.classesName

    if (formData.id) {
      await updateRosterRecord(formData)
      ElMessage.success('更新成功')
    } else {
      await addRosterRecord(formData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    fetchRosterRecordList()
  } catch (error) {
    console.error('提交表单失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data.msg || '操作失败')
    }
  }
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该排班记录吗?', '警告', {
    confirmButtonText: '确定', 
    cancelButtonText: '取消', 
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRosterRecord(id)
      ElMessage.success('删除成功')
      fetchRosterRecordList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 周期模板操作
const handleAddCycle = () => {
  cycleDialogTitle.value = '新增周期模板'
  Object.keys(cycleFormData).forEach(key => {
    if (key !== 'items') cycleFormData[key] = key === 'isEnabled' ? 1 : ''
  })
  cycleFormData.id = null
  cycleFormData.items = []
  cycleDialogVisible.value = true
}

const handleEditCycle = async (row) => {
  try {
    const { data } = await getCycleDetail(row.id)
    if (data) {
      cycleDialogTitle.value = '编辑周期模板'
      Object.assign(cycleFormData, data)
      cycleDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取周期模板详情失败:', error)
    ElMessage.error('获取周期模板详情失败')
  }
}

const submitCycleForm = async () => {
  if (!cycleFormRef.value) return
  
  try {
    await cycleFormRef.value.validate()

    if (cycleFormData.id) {
      await updateCycle(cycleFormData)
      ElMessage.success('更新成功')
    } else {
      await addCycle(cycleFormData)
      ElMessage.success('新增成功')
    }

    cycleDialogVisible.value = false
    fetchCycleList()
  } catch (error) {
    console.error('提交周期表单失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data.msg || '操作失败')
    }
  }
}

const handleDeleteCycle = (id) => {
  ElMessageBox.confirm('确认删除该周期模板吗?', '警告', {
    confirmButtonText: '确定', 
    cancelButtonText: '取消', 
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCycle(id)
      ElMessage.success('删除成功')
      fetchCycleList()
    } catch (error) {
      console.error('删除周期模板失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 一键排班
const handleOneClickRoster = () => {
  oneClickDialogVisible.value = true
}

const submitOneClickRoster = async () => {
  if (!oneClickFormRef.value) return
  
  try {
    await oneClickFormRef.value.validate()
    await oneClickRoster(oneClickForm)
    ElMessage.success('一键排班成功')
    oneClickDialogVisible.value = false
    fetchRosterRecordList()
  } catch (error) {
    console.error('一键排班失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data.msg || '一键排班失败')
    }
  }
}

// 日历操作
const prevMonth = () => {
  const [year, month] = calendarDate.value.split('-').map(Number)
  const newMonth = month === 1 ? 12 : month - 1
  const newYear = month === 1 ? year - 1 : year
  calendarDate.value = `${newYear}-${String(newMonth).padStart(2, '0')}`
  fetchMonthViewData()
}

const nextMonth = () => {
  const [year, month] = calendarDate.value.split('-').map(Number)
  const newMonth = month === 12 ? 1 : month + 1
  const newYear = month === 12 ? year + 1 : year
  calendarDate.value = `${newYear}-${String(newMonth).padStart(2, '0')}`
  fetchMonthViewData()
}

const goToToday = () => {
  calendarDate.value = new Date().toISOString().slice(0, 7)
  fetchMonthViewData()
}

const handleDayClick = (day) => {
  if (day.isCurrentMonth) {
    selectedDate.value = day.date
    selectedDayRosters.value = day.rosterData || []
    calendarDetailVisible.value = true
  }
}

const handleRosterClick = (roster, day) => {
  selectedDate.value = day.date
  selectedDayRosters.value = day.rosterData || []
  calendarDetailVisible.value = true
}

const handleEditFromCalendar = async (roster) => {
 await handleEdit(roster)
  calendarDetailVisible.value = false
  fetchMonthViewData()
}

const handleDeleteFromCalendar = async (id) => {
  await handleDelete(id)
  calendarDetailVisible.value = false
  fetchMonthViewData()
}

const handleAddFromCalendar = () => {
   handleAdd()
  calendarDetailVisible.value = false
  formData.rosterDate = selectedDate.value

  fetchMonthViewData()
}

onMounted(() => {
  fetchPersonList()
  fetchClassesList()
  fetchCycleClassesList()
  fetchCycleList()
  fetchRosterRecordList()
  fetchMonthViewData()
})
</script>

<style scoped>
.operation-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.operation-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

/* 日历样式 */
.calendar-card {
  margin-top: 20px;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.calendar-weekday {
  padding: 12px;
  text-align: center;
  font-weight: bold;
  color: #606266;
}

.calendar-body {
  min-height: 500px;
}

.calendar-week {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  border-bottom: 1px solid #e4e7ed;
}

.calendar-day {
  min-height: 100px;
  padding: 8px;
  border-right: 1px solid #e4e7ed;
  cursor: pointer;
  transition: background-color 0.3s;
}

.calendar-day:last-child {
  border-right: none;
}

.calendar-day:hover {
  background-color: #f5f7fa;
}

.calendar-day.current-month {
  background-color: white;
}

.calendar-day:not(.current-month) {
  background-color: #fafafa;
  color: #c0c4cc;
}

.calendar-day.today {
  background-color: #ecf5ff;
}

.calendar-day.has-data {
  background-color: #f0f9ff;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.day-number {
  font-size: 14px;
  font-weight: bold;
}

.today-badge {
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.day-content {
  max-height: 60px;
  overflow-y: auto;
}

.roster-item {
  margin-bottom: 2px;
}

.roster-item .el-tag {
  width: 100%;
  justify-content: center;
}

/* 周期明细样式 */
.cycle-details {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.day-label {
  min-width: 60px;
  font-weight: bold;
}
</style>